import 'package:enterprise_v6_app/app/components/dialog/custom_general_dialog.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_detail_by_id_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/quiz_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/result/model.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/education/iface.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

/// 测试 / 每日一练 ... 的配置
class QuizConfig {
  QuizConfig({
    required this.type,
    required this.topics,
    this.leftSeconds = 0,
    this.textbookId,
    this.planId,
    this.surveys,
  }) {
    _leftSeconds = leftSeconds;
  }

  /// 类型
  final QuizType type;

  /// 所有题目
  final List<QuizTopic> topics;

  /// 考试剩余秒
  int leftSeconds;
  late final int _leftSeconds;
  int get spentTime => _leftSeconds - leftSeconds;

  /// 测试结果，如果结果为 null，则表示未交卷
  QuizResultPageData? _result;

  /// 错题数量
  int? wrongCount;

  /// 教材ID
  final String? textbookId;
  final String? planId;
  /// 调研
  final GetDetailByIdEntity? surveys;
  final List<String> surveyIds = [];
  final TextEditingController editCtrl = TextEditingController();
  /// 是否正在交卷
  var isSubmitting = false;

  Future<void> showSelectSurvey() async {
    final children = <Widget>[];
    children.addAll(
      surveys?.surveyTypes?.map(
            (e) => StatefulBuilder(builder: (_, setState) {
              return ListTile(
                leading: Checkbox(
                  onChanged: (val) {
                    setState(() {
                      if (surveyIds.contains(e.surveyTypeDicId)) {
                        surveyIds.remove(e.surveyTypeDicId);
                      } else if (e.surveyTypeDicId != null) {
                        surveyIds.add(e.surveyTypeDicId!);
                      }
                    });
                  },
                  value: surveyIds.contains(e.surveyTypeDicId),
                ),
                title: Text(e.surveyTypeDicName ?? ''),
                contentPadding: EdgeInsets.zero,
              );
            }),
          ) ??
          [],
    );
    children.addAll([
      const Text('我的建议'),
      AppGaps.vGap10,
      TextField(
        controller: editCtrl,
        maxLines: 3,
        decoration: InputDecoration(
          hintText: '请输入您的建议',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(5),
            borderSide: const BorderSide(
              color: Color(0xFFEBEDF0),
            ),
          ),
          hintStyle: const TextStyle(
            color: Color(0xFFB4B4B4),
            fontSize: 14,
          ),
          fillColor: const Color(0xFFF7F7FB),
          filled: true,
        ),
      ),
    ]);
    await Get.dialog(CustomGeneralDialog(
      title: '请选择学习专题',
      height: 677.w,
      width: 337.w,
      child: SizedBox(
        height: 590.w,
        width: 337.w,
        child: ListView(
          children: children,
        ),
      ),
    ));
  }

  /// 交卷
  Future<void> onFinish() async {
    // 只能交卷一次
    if (_result != null) throw Exception('不能重复交卷');
    if (isSubmitting) return;
    isSubmitting = true;

    if (surveys != null) {
      await showSelectSurvey();
      await EduQuizIface.submitDemandResearch(
        surveys?.id,
        topics,
        textbookId,
        spentTime,
        planId,
        surveyIds,
        editCtrl.text,
      );
    } else if (textbookId != null) {
      await EduQuizIface.submitQuiz(topics, textbookId!, spentTime, planId);
    }

    final controller = Get.find<EducationQuizController>();
    final correctCount = topics.fold(0, (pre, e) => pre + (e.isAnswerRight ? 1 : 0));
    final notAnswerCount = notAnsweredCount;
    final answeredCount = topics.length - notAnswerCount;
    wrongCount = topics.length - correctCount;

    switch (type) {
      case QuizType.demandTest:
        _result = QuizResultPageData(
          summary: {
            '答题数': answeredCount.toString(),
            '答对数': correctCount.toString(),
            '答错数': wrongCount.toString(),
            '未答数': notAnswerCount.toString(),
          },
          image: AppImages.icon_red_cal,
          title: '已选择专题',
          subtitle: surveyIds.map((e) => surveys?.surveyTypes?.firstWhere((element) => element.surveyTypeDicId == e).surveyTypeDicName).join('、'),
          onTapTitle: () {
            if (wrongCount == 0) {
              AppToast.showWarning('没有错题');
              return;
            }
            controller.config.removeCorrectQuizs();
            controller.currentQuizIdx = 0;
            if (controller.currentQuiz.isAnswerRight) controller.onSlide(false, true);
            Get.back();
          },
          advice: editCtrl.text,
        );
        break;
      case QuizType.dailyLearn:
        _result = QuizResultPageData(
          summary: {
            '答题数': answeredCount.toString(),
            '答对数': correctCount.toString(),
            '答错数': wrongCount.toString(),
            '未答数': notAnswerCount.toString(),
          },
          image: AppImages.icon_red_cal,
          title: '本次错题（$wrongCount道）',
          subtitle: '趁热打铁，巩固本次错题',
          onTapTitle: () {
            if (wrongCount == 0) {
              AppToast.showWarning('没有错题');
              return;
            }
            controller.config.removeCorrectQuizs();
            controller.currentQuizIdx = 0;
            if (controller.currentQuiz.isAnswerRight) controller.onSlide(false, true);
            Get.back();
          },
        );
        break;
      case QuizType.monthTest:
      case QuizType.lessonTest:
        final minutes = spentTime ~/ 60;
        final seconds = spentTime % 60;

        _result = QuizResultPageData(
          summary: {
            '总分': topics.fold(0, (pre, e) => pre + (e.isAnswerRight ? e.score : 0)).toString(),
            '答题数': answeredCount.toString(),
            '用时': '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}',
          },
          image: AppImages.icon_red_cal,
          title: '本次错题（$wrongCount道）',
          subtitle: '趁热打铁，巩固本次错题',
          onTapTitle: () {
            if (wrongCount == 0) {
              AppToast.showWarning('没有错题');
              return;
            }
            controller.config.removeCorrectQuizs();
            controller.currentQuizIdx = 0;
            if (controller.currentQuiz.isAnswerRight) controller.onSlide(false, true);
            Get.back();
          },
        );
        break;
    }
    if (Get.currentRoute != AppRoutes.quizResultPage) Get.toNamed(AppRoutes.quizResultPage);
  }

  QuizResultPageData? get result => _result;

  /// 是否交卷
  bool get isFinished => _result != null;

  /// 没有回答的题目的数量
  int get notAnsweredCount => topics.fold(0, (pre, e) => pre + (e.isAnswered ? 0 : 1));

  void removeCorrectQuizs() {
    topics.removeWhere((element) => element.isAnswerRight);
  }
}

enum QuizType {
  dailyLearn,
  lessonTest,
  monthTest,
  demandTest,
  ;

  /// 是否计时
  bool get watchTime {
    switch (this) {
      case dailyLearn:
        return false;
      case lessonTest:
      case monthTest:
      case demandTest:
        return true;
    }
  }

  String get title {
    switch (this) {
      case dailyLearn:
        return '每日一学';
      case lessonTest:
        return '课程测试';
      case monthTest:
        return '月度测试';
      case demandTest:
        return '需求测试';
    }
  }

  /// 历史记录界面的标题
  String get historyTitle {
    switch (this) {
      case dailyLearn:
        return '每日一测记录';
      case lessonTest:
        return '课程测试记录';
      case monthTest:
        return '月考记录';
      case demandTest:
        return '需求测试记录';
    }
  }
}

/// 单个题目
class QuizTopic {
  QuizTopic({
    required this.id,
    required this.question,
    required this.options,
    List<int>? answers,
    this.score = 0,
    this.explain,
  }) {
    this.answers = answers ?? [];
  }

  final String id;
  final String question;
  late final List<int> answers;
  final List<String> options;
  final int score;

  /// 答案解释
  String? explain;

  /// 当前选中的选项
  List<int> selectedIdx = [];

  /// 是否是多选题
  bool get isMulti => answers.length > 1;

  /// 是否已经回答
  bool get isAnswered => selectedIdx.isNotEmpty;

  /// 是否已选择了当前索引
  bool isSelectedIdx(int idx) => selectedIdx.contains(idx);

  /// 当前答案是否正确
  bool get isAnswerRight {
    return selectedIdx.length == answers.length && selectedIdx.every(answers.contains);
  }

  /// 答案 str
  String get answerStr {
    return answers.map((e) => String.fromCharCode(65 + e)).join('、');
  }

  /// 选择的选项 str
  String get selectedStr {
    if (selectedIdx.isEmpty) return '未选择';
    return selectedIdx.map((e) => String.fromCharCode(65 + e)).join('、');
  }
}

enum QuizTextSize {
  small,
  middle,
  big,
  ;

  int get toInt {
    switch (this) {
      case small:
        return 13;
      case middle:
        return 17;
      case big:
        return 23;
    }
  }
}

class QuizLeftTime {
  QuizLeftTime({required this.hours, required this.minutes, required this.seconds});

  final int hours;
  final int minutes;
  final int seconds;
}
